/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.put.dcs_modeler.wizards.newCFMProject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import org.netbeans.spi.project.ui.support.ProjectChooser;
import org.openide.WizardDescriptor;
import org.openide.WizardValidationException;
import org.openide.filesystems.FileUtil;
import org.openide.util.Exceptions;

public class CFMPanelVisual extends JPanel implements DocumentListener
{
    private static Logger log =
            Logger.getLogger( CFMPanelVisual.class.getName() );
    public static final String PROP_PROJECT_NAME = "projectName";
    private CFMWizardPanel panel;

    public CFMPanelVisual( CFMWizardPanel panel )
    {
        initComponents();
        this.panel = panel;
        // Register listener on the textFields to make the automatic updates
        projectNameTextField.getDocument().addDocumentListener( this );
        projectLocationTextField.getDocument().addDocumentListener( this );
    }

    public String getProjectName()
    {
        return this.projectNameTextField.getText();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        projectNameLabel = new javax.swing.JLabel();
        projectNameTextField = new javax.swing.JTextField();
        projectLocationLabel = new javax.swing.JLabel();
        projectLocationTextField = new javax.swing.JTextField();
        browseButton = new javax.swing.JButton();
        createdFolderLabel = new javax.swing.JLabel();
        createdFolderTextField = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        datamodelLocation = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JSeparator();
        jLabel3 = new javax.swing.JLabel();
        serverDirJTxt = new javax.swing.JTextField();
        serverButton = new javax.swing.JButton();

        projectNameLabel.setLabelFor(projectNameTextField);
        org.openide.awt.Mnemonics.setLocalizedText(projectNameLabel, org.openide.util.NbBundle.getMessage(CFMPanelVisual.class, "CFMPanelVisual.projectNameLabel.text")); // NOI18N

        projectLocationLabel.setLabelFor(projectLocationTextField);
        org.openide.awt.Mnemonics.setLocalizedText(projectLocationLabel, org.openide.util.NbBundle.getMessage(CFMPanelVisual.class, "CFMPanelVisual.projectLocationLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(browseButton, org.openide.util.NbBundle.getMessage(CFMPanelVisual.class, "CFMPanelVisual.browseButton.text")); // NOI18N
        browseButton.setActionCommand(org.openide.util.NbBundle.getMessage(CFMPanelVisual.class, "CFMPanelVisual.browseButton.actionCommand")); // NOI18N
        browseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                browseButtonActionPerformed(evt);
            }
        });

        createdFolderLabel.setLabelFor(createdFolderTextField);
        org.openide.awt.Mnemonics.setLocalizedText(createdFolderLabel, org.openide.util.NbBundle.getMessage(CFMPanelVisual.class, "CFMPanelVisual.createdFolderLabel.text")); // NOI18N

        createdFolderTextField.setEditable(false);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(CFMPanelVisual.class, "CFMPanelVisual.jLabel1.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(CFMPanelVisual.class, "CFMPanelVisual.jLabel2.text")); // NOI18N

        datamodelLocation.setText(org.openide.util.NbBundle.getMessage(CFMPanelVisual.class, "CFMPanelVisual.datamodelLocation.text")); // NOI18N
        datamodelLocation.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                datamodelLocationActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jButton1, org.openide.util.NbBundle.getMessage(CFMPanelVisual.class, "CFMPanelVisual.jButton1.text")); // NOI18N
        jButton1.setActionCommand(org.openide.util.NbBundle.getMessage(CFMPanelVisual.class, "CFMPanelVisual.jButton1.actionCommand")); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(CFMPanelVisual.class, "CFMPanelVisual.jLabel3.text")); // NOI18N

        serverDirJTxt.setText(org.openide.util.NbBundle.getMessage(CFMPanelVisual.class, "CFMPanelVisual.serverDirJTxt.text")); // NOI18N
        serverDirJTxt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                serverDirJTxtActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(serverButton, org.openide.util.NbBundle.getMessage(CFMPanelVisual.class, "CFMPanelVisual.serverButton.text")); // NOI18N
        serverButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                serverButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(projectNameLabel)
                    .addComponent(projectLocationLabel)
                    .addComponent(createdFolderLabel))
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(createdFolderTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 334, Short.MAX_VALUE)
                    .addComponent(projectNameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 334, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(projectLocationTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(browseButton)))
                .addContainerGap())
            .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 445, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addContainerGap(94, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(datamodelLocation, javax.swing.GroupLayout.DEFAULT_SIZE, 238, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addComponent(jSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 445, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addContainerGap(274, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(serverDirJTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 337, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(serverButton, javax.swing.GroupLayout.DEFAULT_SIZE, 82, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(projectNameLabel)
                    .addComponent(projectNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(projectLocationLabel)
                    .addComponent(browseButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(projectLocationTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(createdFolderLabel)
                    .addComponent(createdFolderTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(datamodelLocation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(serverDirJTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(serverButton, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(39, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseButtonActionPerformed
        String command = evt.getActionCommand();
        if ( "BROWSE".equals( command ) )
        {
            JFileChooser chooser = new JFileChooser();
            FileUtil.preventFileChooserSymlinkTraversal( chooser, null );
            chooser.setDialogTitle( "Select Project Location" );
            chooser.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );
            String path = this.projectLocationTextField.getText();
            if ( path.length() > 0 )
            {
                File f = new File( path );
                if ( f.exists() )
                {
                    chooser.setSelectedFile( f );
                }
            }
            if ( JFileChooser.APPROVE_OPTION == chooser.showOpenDialog( this ) )
            {
                File projectDir = chooser.getSelectedFile();
                projectLocationTextField.setText( FileUtil.normalizeFile( projectDir ).getAbsolutePath() );
            }
            panel.fireChangeEvent();
        }

    }//GEN-LAST:event_browseButtonActionPerformed

private void datamodelLocationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_datamodelLocationActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_datamodelLocationActionPerformed

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    String command = evt.getActionCommand();
    if ( "BROWSE".equals( command ) )
    {
        JFileChooser chooser = new JFileChooser();
        FileUtil.preventFileChooserSymlinkTraversal( chooser, null );
        chooser.setDialogTitle( "Select datamodel location" );
        chooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
        String path = this.datamodelLocation.getText();
        if ( path.length() > 0 )
        {
            File f = new File( path );
            if ( f.exists() )
            {
                chooser.setSelectedFile( f );
            }
        }
        if ( JFileChooser.APPROVE_OPTION == chooser.showOpenDialog( this ) )
        {
            File projectDir = chooser.getSelectedFile();
            datamodelLocation.setText( FileUtil.normalizeFile( projectDir ).getAbsolutePath() );
        }
        panel.fireChangeEvent();
    }// TODO add your handling code here:
}//GEN-LAST:event_jButton1ActionPerformed

private void serverButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_serverButtonActionPerformed
{//GEN-HEADEREND:event_serverButtonActionPerformed
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle( "Select server publication dir" );
    chooser.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );
    String path = this.serverDirJTxt.getText();
    if ( path.length() > 0 )
    {
        File f = new File( path );
        if ( f.exists() )
        {
            chooser.setSelectedFile( f );
        }
    }
    if ( JFileChooser.APPROVE_OPTION == chooser.showOpenDialog( this ) )
    {
        serverDirJTxt.setText( chooser.getSelectedFile().getPath() );
    }
}//GEN-LAST:event_serverButtonActionPerformed

public String getServerPath()
{
    return serverDirJTxt.getText();
}
private void serverDirJTxtActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_serverDirJTxtActionPerformed
{//GEN-HEADEREND:event_serverDirJTxtActionPerformed
    // TODO add your handling code here:
}//GEN-LAST:event_serverDirJTxtActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton browseButton;
    private javax.swing.JLabel createdFolderLabel;
    private javax.swing.JTextField createdFolderTextField;
    private javax.swing.JTextField datamodelLocation;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JLabel projectLocationLabel;
    private javax.swing.JTextField projectLocationTextField;
    private javax.swing.JLabel projectNameLabel;
    private javax.swing.JTextField projectNameTextField;
    private javax.swing.JButton serverButton;
    private javax.swing.JTextField serverDirJTxt;
    // End of variables declaration//GEN-END:variables
    @Override
    public void addNotify()
    {
        super.addNotify();
        //same problem as in 31086, initial focus on Cancel button
        projectNameTextField.requestFocus();
    } 
    
    public Boolean isDataModelCorrectPath()
    {
        // File dmJar = FileUtil.normalizeFile( new File( dmJarPath ) );

        FileInputStream in = null;
        String dmJarPath = this.datamodelLocation.getText();
        try
        {
            in = new FileInputStream( dmJarPath );
            ZipInputStream str = new ZipInputStream( in );
            ZipEntry entry;
            if ( ( entry = str.getNextEntry() ) != null )
            {
                return true;
            }
        } catch ( IOException ex )
        {
            log.warning( ex.getMessage() );
            //Exceptions.printStackTrace( ex );
        } finally
        {
            try
            {
                in.close();
            } catch ( IOException ex )
            {
                log.warning( ex.getMessage() );
                // Exceptions.printStackTrace( ex );
            }
        }
        return false;
    }
    
    boolean valid( WizardDescriptor wizardDescriptor )
    {

        if ( projectNameTextField.getText().length() == 0 )
        {
            wizardDescriptor.putProperty( "WizardPanel_errorMessage",
                    "Project Name is not a valid folder name." );
            return false; // Display name not specified
        }
        File f = FileUtil.normalizeFile( new File( projectLocationTextField.getText() ).getAbsoluteFile() );
        if ( !f.isDirectory() )
        {
            String message = "Project Folder is not a valid path.";
            wizardDescriptor.putProperty( "WizardPanel_errorMessage", message );
            return false;
        }
        final File destFolder = FileUtil.normalizeFile( new File( createdFolderTextField.getText() ).getAbsoluteFile() );

        File projLoc = destFolder;
        while ( projLoc != null && !projLoc.exists() )
        {
            projLoc = projLoc.getParentFile();
        }
        if ( projLoc == null || !projLoc.canWrite() )
        {
            wizardDescriptor.putProperty( "WizardPanel_errorMessage",
                    "Project Folder cannot be created." );
            return false;
        }

        if ( FileUtil.toFileObject( projLoc ) == null )
        {
            String message = "Project Folder is not a valid path.";
            wizardDescriptor.putProperty( "WizardPanel_errorMessage", message );
            return false;
        }

        File[] kids = destFolder.listFiles();
        if ( destFolder.exists() && kids != null && kids.length > 0 )
        {
            // Folder exists and is not empty
            wizardDescriptor.putProperty( "WizardPanel_errorMessage",
                    "Project Folder already exists and is not empty." );
            return false;
        }
        
        if ( ( this.datamodelLocation.getText().length() == 0 ) || ( !isDataModelCorrectPath() ) )
        {
            log.info( "test validate");
            wizardDescriptor.putProperty( "WizardPanel_errorMessage",
                    "It isn't correct datamodel path" );
            return false;
        }
        
        wizardDescriptor.putProperty( "WizardPanel_errorMessage", "" );
        return true;
    }

    void store( WizardDescriptor d )
    {
        String name = projectNameTextField.getText().trim();
        String folder = createdFolderTextField.getText().trim();
        String dmJarDir = datamodelLocation.getText().trim();
        String serverDir = serverDirJTxt.getText().trim();

        d.putProperty( "projdir", new File( folder ) );
        d.putProperty( "name", name );
        d.putProperty( "dmJarPath", dmJarDir );
        d.putProperty( "serverPath", serverDir );
    }

    void read( WizardDescriptor settings )
    {
        File projectLocation = ( File ) settings.getProperty( "projdir" );
        if ( projectLocation == null || projectLocation.getParentFile() == null || !projectLocation.getParentFile().isDirectory() )
        {
            projectLocation = ProjectChooser.getProjectsFolder();
        } else
        {
            projectLocation = projectLocation.getParentFile();
        }
        this.projectLocationTextField.setText( projectLocation.getAbsolutePath() );

        String projectName = ( String ) settings.getProperty( "name" );
        if ( projectName == null )
        {
            projectName = "CFM";
        }
        String dmPath = ( String )settings.getProperty( "dmJarPath" );
        this.datamodelLocation.setText( dmPath );
        this.projectNameTextField.setText( projectName );
        this.projectNameTextField.selectAll();

        this.serverDirJTxt.setText( ( String )settings.getProperty( "serverPath" ) );

    }

    void validate( WizardDescriptor d ) throws WizardValidationException
    {
        // nothing to validate
    }

    // Implementation of DocumentListener --------------------------------------
    public void changedUpdate( DocumentEvent e )
    {
        updateTexts( e );
        if ( this.projectNameTextField.getDocument() == e.getDocument() )
        {
            firePropertyChange( PROP_PROJECT_NAME, null, this.projectNameTextField.getText() );
        }
    }

    public void insertUpdate( DocumentEvent e )
    {
        updateTexts( e );
        if ( this.projectNameTextField.getDocument() == e.getDocument() )
        {
            firePropertyChange( PROP_PROJECT_NAME, null, this.projectNameTextField.getText() );
        }
    }

    public void removeUpdate( DocumentEvent e )
    {
        updateTexts( e );
        if ( this.projectNameTextField.getDocument() == e.getDocument() )
        {
            firePropertyChange( PROP_PROJECT_NAME, null, this.projectNameTextField.getText() );
        }
    }

    /** Handles changes in the Project name and project directory, */
    private void updateTexts( DocumentEvent e )
    {

        Document doc = e.getDocument();

        if ( doc == projectNameTextField.getDocument() || doc == projectLocationTextField.getDocument() )
        {
            // Change in the project name

            String projectName = projectNameTextField.getText();
            String projectFolder = projectLocationTextField.getText();

            //if (projectFolder.trim().length() == 0 || projectFolder.equals(oldName)) {
            createdFolderTextField.setText( projectFolder + File.separatorChar + projectName );
        //}

        }
        panel.fireChangeEvent(); // Notify that the panel changed
    }
}
